package com.itheima.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 安全框架在验证时默认认为你的密码是加密的
 * 配置  {noop} ， 没有加密
 *
 *@EnableGlobalMethodSecurity: 允许使用注解的方式控制权限
 * prePostEnabled: 允许使用 @PreAuthorize, @PostAuthorize
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity //开启web认证
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

//    @Override
//    @Bean
//    protected UserDetailsService userDetailsService() {
////        //在内存中管理用户详情信息
//        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
////        //创建用户对象
//        userDetailsManager.createUser(
//                User.withUsername("admin")
//                    .password("$2a$10$hNsxvH9GHgHZ6c35CkHCuuUTgnbnR9i2TO4QVUhy5fd2tEbncAgj6").authorities("P1", "ROLE_ADMIN").build());
//
//        userDetailsManager.createUser(
//                User.withUsername("test")
//                        .password("$2a$10$hNsxvH9GHgHZ6c35CkHCuuUTgnbnR9i2TO4QVUhy5fd2tEbncAgj6").authorities("O1", "test").build());
//        return userDetailsManager;
//    }

    /**
     * csrf: 跨站请求伪造
     * csrf().disable(): 关闭跨站请求伪造
     *
     * permitAll: 放行（不需要认证）
     * hasRole: 是否拥有某个角色
     *
     * antMatchers("hello").hasRole("ADMIN"):  hello请求必须是 ADMIN 角色
     * antMatchers("say").hasAuthority("O1"); say 请求必须 有 O1 权限'
     * anyRequest().authenticated()  其他的请求，只要认证了就可以访问
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .and()
                .csrf().disable()
                .logout().and().authorizeRequests()
                .antMatchers("/register").permitAll()
//                .antMatchers("/hello").hasRole("ADMIN")
//                .antMatchers("/say").hasAuthority("O1")
                .anyRequest().authenticated();
    }
}
